<script type="text/javascript">
    var plistcount;
    var plidx;
    var vlc_name = "vlc_playback";
    var curtime;
    var arrMonthSort = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Agu", "Sep", "Oct", "Nov", "Dec"];
    var startTime;
    var totalrequest;
    var reqinterval;
    
    function init()
    {
        doPlaylistClearAll();
        
        if( navigator.appName.indexOf("Microsoft Internet")==-1 )
        {
            onVLCPluginReady()
        }
        else if( document.readyState == 'complete' )
        {
            onVLCPluginReady();
        }
        else
        {
            /* Explorer loads plugins asynchronously */
            document.onreadystatechange=function()
            {
                if( document.readyState == 'complete' )
                {
                    onVLCPluginReady();
                }
            }
        }
    }
    
    function doPlaylistClearAll()
    {
        var vlc = getVLC(vlc_name);
        if( vlc )
        {
            vlc.playlist.items.clear();
            while( vlc.playlist.items.count > 0)
            {
                // wait till playlist empties.
            }
            //doItemCount();
        }
    }

    function getVLC(name)
    {
        if (window.document[name])
        {
            return window.document[name];
        }
        if (navigator.appName.indexOf("Microsoft Internet")==-1)
        {
            if (document.embeds && document.embeds[name])
                return document.embeds[name];
        }
        else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
        {
            return document.getElementById(name);
        }
    }
    
    function handle_MediaPlayerPlaying()
    {
        onPlay();
    }
    
    function onPlay()
    {
        document.getElementById('txtstate').innerHTML = plidx + ' of ' + plistcount;
        onPlaying();
    }

    function onPlaying()
    {
        var vlc = getVLC(vlc_name);
        var info = document.getElementById("info");
        if( vlc )
        {
            var mediaLen = vlc.input.length;
            if( mediaLen > 0 )
            {
                // seekable media
                info.innerHTML = formatTime(vlc.input.time)+"/"+formatTime(mediaLen);
            }
            else
            {
                // non-seekable "live" media
                liveFeedRoll = liveFeedRoll & 3;
                info.innerHTML = liveFeedText[liveFeedRoll++];
            }
        }
    }
    
    function handle_MediaPlayerTimeChanged(time)
    {
        var vlc = getVLC(vlc_name);
        var info = document.getElementById("info");
        if( vlc )
        {
            var mediaLen = vlc.input.length;
            if( mediaLen > 0 )
            {
                // seekable media
                info.innerHTML = formatTime(time)+"/"+formatTime(mediaLen);
                curtime = time;
                var dt = new Date(startTime + curtime);
                document.getElementById('txtrealtime').innerHTML =
                        getLeadingZero(dt.getDate()) + ' - ' +
                        getLeadingZero(arrMonthSort[dt.getMonth()]) + ' - ' +
                        parseInt(dt.getYear()+1900) + ' ' +
                        getLeadingZero(dt.getHours()) + ':' +
                        getLeadingZero(dt.getMinutes()) + ':' +
                        getLeadingZero(dt.getSeconds()) + '.' +
                        (dt.getMilliseconds()<=9?"00"+dt.getMilliseconds():dt.getMilliseconds()<=99?"0"+dt.getMilliseconds():dt.getMilliseconds());
            }
        }
    }
    
    function getLeadingZero(numinput){
        if (numinput<=9){
            return "0"+numinput;
        }else{
            return numinput;
        }
    }
    
    function formatTime(timeVal)
    {
        if( typeof timeVal != 'number' )
            return "-:--:--";

        var timeHour = Math.round(timeVal / 1000);
        var timeSec = timeHour % 60;
        if( timeSec < 10 )
            timeSec = '0'+timeSec;
        timeHour = (timeHour - timeSec)/60;
        var timeMin = timeHour % 60;
        if( timeMin < 10 )
            timeMin = '0'+timeMin;
        timeHour = (timeHour - timeMin)/60;
        if( timeHour > 0 )
            return timeHour+":"+timeMin+":"+timeSec;
        else
            return timeMin+":"+timeSec;
    }

    function handle_MediaPlayerEndReached()
    {
        onEnd();
    }
    
    function registerVLCEvent(event, handler)
    {
        var vlc = getVLC(vlc_name);

        if (vlc) {
            if (vlc.attachEvent) {
                // Microsoft
                vlc.attachEvent (event, handler);
            } else if (vlc.addEventListener) {
                // Mozilla: DOM level 2
                vlc.addEventListener (event, handler, true);
            } else {
                // DOM level 0
                eval("vlc_playback.on" + event + " = handler");
            }
        }
    }

    function unregisterVLCEvent(event, handler)
    {
        var vlc = getVLC(vlc_name);

        if (vlc) {
            if (vlc.detachEvent) {
                // Microsoft
                vlc.detachEvent (event, handler);
            } else if (vlc.removeEventListener) {
                // Mozilla: DOM level 2
                vlc.removeEventListener (event, handler, true);
            } else {
                // DOM level 0
                eval("vlc_playback.on" + event + " = null");
            }
        }
    }
    
    function onVLCPluginReady()
    {
//        registerVLCEvent("MediaPlayerMediaChanged", handleMediaPlayerMediaChanged);
//        registerVLCEvent("MediaPlayerNothingSpecial", handle_MediaPlayerNothingSpecial);
//        registerVLCEvent("MediaPlayerOpening", handle_MediaPlayerOpening);
//        registerVLCEvent("MediaPlayerBuffering", handle_MediaPlayerBuffering);
        registerVLCEvent("MediaPlayerPlaying", handle_MediaPlayerPlaying);
//        registerVLCEvent("MediaPlayerPaused", handle_MediaPlayerPaused);
//        registerVLCEvent("MediaPlayerStopped", handle_MediaPlayerStopped);
//        registerVLCEvent("MediaPlayerForward", handle_MediaPlayerForward);
//        registerVLCEvent("MediaPlayerBackward", handle_MediaPlayerBackward);
        registerVLCEvent("MediaPlayerEndReached", handle_MediaPlayerEndReached);
//        registerVLCEvent("MediaPlayerEncounteredError", handle_MediaPlayerEncounteredError);
        registerVLCEvent("MediaPlayerTimeChanged", handle_MediaPlayerTimeChanged);
//        registerVLCEvent("MediaPlayerPositionChanged", handle_MediaPlayerPositionChanged);
//        registerVLCEvent("MediaPlayerSeekableChanged", handle_MediaPlayerSeekableChanged);
//        registerVLCEvent("MediaPlayerPausableChanged", handle_MediaPlayerPausableChanged);
//        registerVLCEvent("MediaPlayerTitleChanged", handle_MediaPlayerTitleChanged);
//        registerVLCEvent("MediaPlayerLengthChanged", handle_MediaPlayerLengthChanged);
    }

    function close()
    {
//        unregisterVLCEvent("MediaPlayerMediaChanged", handleMediaPlayerMediaChanged);
//        unregisterVLCEvent("MediaPlayerNothingSpecial", handle_MediaPlayerNothingSpecial);
//        unregisterVLCEvent("MediaPlayerOpening", handle_MediaPlayerOpening);
//        unregisterVLCEvent("MediaPlayerBuffering", handle_MediaPlayerBuffering);
        unregisterVLCEvent("MediaPlayerPlaying", handle_MediaPlayerPlaying);
//        unregisterVLCEvent("MediaPlayerPaused", handle_MediaPlayerPaused);
//        unregisterVLCEvent("MediaPlayerStopped", handle_MediaPlayerStopped);
//        unregisterVLCEvent("MediaPlayerForward", handle_MediaPlayerForward);
//        unregisterVLCEvent("MediaPlayerBackward", handle_MediaPlayerBackward);
        unregisterVLCEvent("MediaPlayerEndReached", handle_MediaPlayerEndReached);
//        unregisterVLCEvent("MediaPlayerEncounteredError", handle_MediaPlayerEncounteredError);
        unregisterVLCEvent("MediaPlayerTimeChanged", handle_MediaPlayerTimeChanged);
//        unregisterVLCEvent("MediaPlayerPositionChanged", handle_MediaPlayerPositionChanged);
//        unregisterVLCEvent("MediaPlayerSeekableChanged", handle_MediaPlayerSeekableChanged);
//        unregisterVLCEvent("MediaPlayerPausableChanged", handle_MediaPlayerPausableChanged);
//        unregisterVLCEvent("MediaPlayerTitleChanged", handle_MediaPlayerTitleChanged);
//        unregisterVLCEvent("MediaPlayerLengthChanged", handle_MediaPlayerLengthChanged);
    }
    
    function doStop()
    {
        var vlc = getVLC(vlc_name);
        if( vlc )
            vlc.playlist.stop();
    }
    
    function doAdd(targetURL)
    {
        var vlc = getVLC(vlc_name);
        var options = [":vout-filter=deinterlace", ":deinterlace-mode=linear"];
        if( vlc )
        {
            var itemId = vlc.playlist.add(targetURL, "", options);
            options = [];
        }
    }
    
    function doGo(targetURL)
    {
        var vlc = getVLC(vlc_name);

        if( vlc )
        {
            vlc.playlist.items.clear();
            while( vlc.playlist.items.count > 0 )
            {
                // clear() may return before the playlist has actually been cleared
                // just wait for it to finish its job
            }
            var options = [":rtsp-tcp"];
            var itemId = vlc.playlist.add(targetURL,"",options);
            options = [];
            if( itemId != -1 )
            {
                // play MRL
                vlc.playlist.playItem(itemId);
            }
            else
            {
                alert("cannot play at the moment !");
            }
            //doItemCount();
        }
    }
    
    function getDateFromString(strtime){
        var time = new Date();
        
        time.setYear(strtime.substr(0,4));
        time.setMonth(parseInt(strtime.substr(4,2))-1);
        time.setDate(parseInt(strtime.substr(6,2)));
        time.setHours(parseInt(strtime.substr(8,2)));
        time.setMinutes(parseInt(strtime.substr(10,2)));
        time.setSeconds(parseInt(strtime.substr(12,2)));
        time.setMilliseconds(parseInt(strtime.substr(14,3)));
        
        return time;
    }
    
    function onEnd()
    {
        startTime += curtime;
        curtime = 0;
        plidx +=1;
        if(plidx>plistcount){
            doPlaylistClearAll();
            $.ajax ({
            type:"POST",
            url:"<?php echo Yii::app()->createUrl('/specialajax/videoplayback'); ?>",
            data:"pl="+document.getElementById('txtpl').value,
            dataType:"json",
                success:function(data){
                    if(data != null){
                        if (data.length>0){
                            startTime = parseInt(getDateFromString(data[0].filename.substr(0,17)).getTime());
                            plidx = 1;
                            plistcount=data.length;
                            var str = document.getElementById('txtpl').value;
                            var str1 = document.getElementById('dlist').innerHTML;

                            for(var i=0;i<data.length;i++){
                                str += data[i].url + '|';
                                str1 += data[i].filename + '<br>';
                                doAdd(data[i].url);
                            }

                            document.getElementById('dlist').innerHTML = str1;
                            document.getElementById('txtpl').value = str;
                        }
                    }else{
                        doStop();
                        close();
                    }
                }
            });
            $.ajax ({
            type:"POST",
            url:"<?php echo Yii::app()->createUrl('/specialajax/endofplaylist'); ?>",
            data:"pl=&co=<?php echo $co; ?>&ca=<?php echo $ca; ?>",
            dataType:"json",
                success:function(data){
                    document.getElementById('txtstate').innerHTML = "End Of Video";
                }
            });
        }
    }
    
    function startFirstVideo(){
        $.ajax ({
        type:"POST",
        url:"<?php echo Yii::app()->createUrl('/specialajax/videoplayback'); ?>",
        data:"pl=&co=<?php echo $co; ?>&ca=<?php echo $ca; ?>",
        dataType:"json",
            success:function(data){
                if(data !== null && data.length>0){
                    if(data[0].filename === 'notfound' && data[0].url === 'notfound'){
                        $.ajax ({
                        type:"POST",
                        url:"<?php echo Yii::app()->createUrl('/specialajax/endofplaylist'); ?>",
                        data:"pl=&co=<?php echo $co; ?>&ca=<?php echo $ca; ?>",
                        dataType:"json",
                            success:function(data){
                                document.getElementById('txtstate').innerHTML = "End Of Video";
                            }
                        });
                        alert('Video not Found!!!');
                        return ;
                    }else{
                        var str = '';
                        var str1 = '';
                        plistcount = data.length;
                        plidx = 1;

                        startTime = parseInt(getDateFromString(data[0].filename.substr(0,17)).getTime());
                        curtime = 0;

                        for(var i=0;i<data.length;i++){
                            str += data[i].url + '|';
                            str1 += data[i].filename + '<br>';
                            doAdd(data[i].url);
                        }
                        var vlc = getVLC(vlc_name);
                        vlc.playlist.playItem(0);

                        document.getElementById('dlist').innerHTML = str1;
                        document.getElementById('txtpl').value = str;
                    }
                }else{
                    document.getElementById('txtstate').innerHTML = "Seaching...";
                    
                    <?php
                        $username = Yii::app()->user->name;
                        $cctvreq = Cctvrequestvideoplayback::model()->find("credentialname = '{$username}' and computername = '$co' and cameraname = '$ca' and isactive = 'true'");
                    ?>

                    <?php if(isset($cctvreq)){?>
                         reqinterval = setTimeout(function(){
                            totalrequest +=1;
                            if (totalrequest>10){
                               alert('Request Video Failed, Maybe Server is not Respoding!!');
                               clearInterval(reqinterval);
                            }else{
                                startFirstVideo();
                            }
                        },2000);
                    <?php }else{ ?>
                        alert('You must Request Video First!!');
                    <?php }?>
                }
            }
        });
    }
    
    $(document).ready(function(){
        totalrequest = 0;
        init();
        startFirstVideo();
    });
    
    $(document).unload(function(){
        close();
    });
</script>

<object classid="clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921"
        width="640"
        height="480"
        id="vlc_playback"
        events="True">
<param name="MRL" value="" />
<param name="ShowDisplay" value="True" />
<param name="AutoLoop" value="False" />
<param name="AutoPlay" value="False" />
<param name="Volume" value="50" />
<param name="toolbar" value="true" />
<param name="StartTime" value="0" />
<EMBED pluginspage="http://www.videolan.org"
       type="application/x-vlc-plugin"
       version="VideoLAN.VLCPlugin.2"
       width="640"
       height="480"
       toolbar="true"
       loop="true"
       text="Waiting for video"
       name="vlc_playback">
</EMBED>
</object>
<br>
<div id="info" style="text-align:left"></div>
<div id="txtrealtime" style="text-align:left"></div>
<div id="txtstate" style="text-align:left"></div>
<input type="text" id="txtpl" value="" size="100" style="visibility: hidden">
<div id="dlist" style="visibility: hidden"></div>